package cn.cxj.user.service.impl;

import cn.cxj.basic.constant.BaseConstants;
import cn.cxj.basic.exception.BusinessException;
import cn.cxj.basic.service.impl.BaseServiceImpl;
import cn.cxj.basic.util.MD5Utils;
import cn.cxj.basic.util.StrUtils;
import cn.cxj.user.domain.Logininfo;
import cn.cxj.user.domain.User;
import cn.cxj.user.dto.UserDto;
import cn.cxj.user.mapper.LogininfoMapper;
import cn.cxj.user.mapper.UserMapper;
import cn.cxj.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;

/**
 * 用户模块业务层实现类
 * @author 陈鑫杰
 * @date 2022-2-5 16:16:27
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {
        // 校验
        // 校验是否为空
        if (StringUtils.isEmpty(userDto.getPhone())
                || StringUtils.isEmpty(userDto.getVerifyCode())
                || StringUtils.isEmpty(userDto.getPassword())
                || StringUtils.isEmpty(userDto.getConfirmPassword())){
            throw new BusinessException("参数错误!");
        }
        // 两次密码是否一致
        if (!userDto.getPassword().equals(userDto.getConfirmPassword())) {
            throw new BusinessException("两次密码输入不一致!");
        }
        // 校验用户名不存在
        User userTemp = userMapper.loadByPhone(userDto.getPhone());
        if (userTemp != null) {
            throw new BusinessException("用户名已存在,请重新输入!");
        }
        // 校验验证码
        Object codeTemp = redisTemplate.opsForValue().get(BaseConstants.BUSINESS_REGISTER_PREFIX + userDto.getPhone());
        // 验证码是否过期
        if (codeTemp == null) {
            throw new BusinessException("验证码已失效,请重新获取!");
        }
        // 验证码是否正确
        String code = ((String)codeTemp).split(":")[0];
        if (!userDto.getVerifyCode().equals(code)) {
            throw new BusinessException("验证码错误!");
        }
        // 存数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 保存logininfo
        logininfoMapper.save(logininfo);
        // 保存user
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailRegister(UserDto userDto) throws Exception{
        // 校验
        // 校验是否为空
        if (StringUtils.isEmpty(userDto.getEmail())
                || StringUtils.isEmpty(userDto.getPassword())
                || StringUtils.isEmpty(userDto.getConfirmPassword())) {
            throw new BusinessException("参数错误");
        }
        // 两次密码是否一致
        if (!userDto.getPassword().equals(userDto.getConfirmPassword())) {
            throw new BusinessException("两次密码输入不一致!");
        }
        // 校验邮箱是否存在
        User userTemp = userMapper.loadByEmail(userDto.getEmail());
        if (userTemp != null) {
            throw new BusinessException("邮箱已经存在,请重新输入!");
        }
        // 存数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 保存logininfo
        logininfoMapper.save(logininfo);
        // 保存user
        user.setLogininfo_id(logininfo.getId());
        user.setState(0);
        userMapper.save(user);
        // 给邮箱发送激活链接
        String email = userDto.getEmail();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("53999356@qq.com");
        helper.setSubject("激活邮件");
        helper.setText("<a href='http://localhost:80/login.html?id=" + user.getId()  + "'>点击激活账号</a>",true);
        helper.setTo("53999356@qq.com");
        // 发送邮件
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void updateStateById(Long id) {
        userMapper.updateStateById(id);
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        if (!StringUtils.isEmpty(userDto.getEmail())) {
            user.setEmail(userDto.getEmail());
        }
        // 盐值加密
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        return logininfo;
    }

}


